import { getToken } from '@/utils/auth'
import { getUserInfo } from '@/api/user'
import { getStoreInfo } from "@/api/homepage";


const state = {
  token: getToken(),
  memberInfo: {},
  roles: [],
  storeInfo: {},
  loginToken: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MEMBER_INFO: (state, data) => {
    state.memberInfo = data
    // console.log('获取到用户信息', state.memberInfo);
    // if (window.performance.navigation.type == 1) {
    //   console.log("页面被刷新111");
    // } else {
    //   console.log("首次被加载111");

    // }
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_STOREINFO: (state, storeInfo) => {
    state.storeInfo = storeInfo
  },
  SET_LOGINTOKEN: (state, loginToken) => {
    state.loginToken = loginToken
  }
}

const actions = {
  getStoreInfo({ commit, state }) {
    
    return new Promise((resolve, reject) => {
      getStoreInfo(state.token).then(res => {
        const { data } = res
        commit('SET_STOREINFO', data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      let loginToken = getToken()
      console.log('登录token333', loginToken);
      getUserInfo(loginToken).then(res => {
        const { data } = res
        if (!data) {
          reject('请重新登录...')
        }
        let roles = []
        if (data.status == 1) {
          roles.push('admin')
        } else {
          roles.push('admin')
        }
        commit('SET_MEMBER_INFO', data)
        commit('SET_ROLES', roles)
        resolve(roles)
      }).catch(error => {
        reject(error)
      })

    })
  },
  setRoles({ commit }, roles) {
    commit('SET_ROLES', roles)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
